/**
 * 智能标题建议弹窗
 * 展示AI生成的多个标题选项供用户选择
 */

import React, { useState, useCallback, useEffect } from 'react'
import { Modal, List, Button, Spin, Alert, Space, Typography, Tag } from 'antd'
import { BulbOutlined, ReloadOutlined, CheckOutlined } from '@ant-design/icons'

const { Text, Paragraph } = Typography

export interface TitleSuggestionModalProps {
  visible: boolean
  onClose: () => void
  onSelect: (title: string) => void
  onGenerate: () => Promise<string[]>
  initialTitles?: string[]
}

const TITLE_STYLES = [
  { label: '平实型', color: 'blue' },
  { label: '吸引型', color: 'orange' },
  { label: '悬念型', color: 'purple' },
  { label: '数字型', color: 'green' },
  { label: '情感型', color: 'red' }
]

const TitleSuggestionModal: React.FC<TitleSuggestionModalProps> = ({
  visible,
  onClose,
  onSelect,
  onGenerate,
  initialTitles
}) => {
  const [titles, setTitles] = useState<string[]>(initialTitles || [])
  const [loading, setLoading] = useState(false)
  const [selectedTitle, setSelectedTitle] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  // 当Modal打开时，如果没有标题则自动生成
  useEffect(() => {
    if (visible && titles.length === 0) {
      handleGenerate()
    }
  }, [visible])

  // 生成标题
  const handleGenerate = useCallback(async () => {
    setLoading(true)
    setError(null)
    setSelectedTitle(null)

    try {
      const newTitles = await onGenerate()
      setTitles(newTitles)

      if (newTitles.length === 0) {
        setError('AI未能生成标题建议，请稍后重试')
      }
    } catch (err) {
      console.error('[TitleSuggestionModal] 生成标题失败:', err)
      setError('生成标题失败，请检查网络连接或AI配置')
    } finally {
      setLoading(false)
    }
  }, [onGenerate])

  // 选择标题
  const handleSelectTitle = useCallback((title: string) => {
    setSelectedTitle(title)
  }, [])

  // 确认选择
  const handleConfirm = useCallback(() => {
    if (selectedTitle) {
      onSelect(selectedTitle)
      onClose()
    }
  }, [selectedTitle, onSelect, onClose])

  // 关闭弹窗时重置状态
  const handleClose = useCallback(() => {
    setSelectedTitle(null)
    setError(null)
    onClose()
  }, [onClose])

  return (
    <Modal
      title={
        <Space>
          <BulbOutlined style={{ color: '#1890ff' }} />
          <span>智能标题</span>
        </Space>
      }
      open={visible}
      onCancel={handleClose}
      width={700}
      footer={
        <Space>
          <Button
            icon={<ReloadOutlined />}
            onClick={handleGenerate}
            loading={loading}
            disabled={loading}
          >
            重新生成
          </Button>
          <Button onClick={handleClose}>
            取消
          </Button>
          <Button
            type="primary"
            icon={<CheckOutlined />}
            onClick={handleConfirm}
            disabled={!selectedTitle || loading}
          >
            使用选中标题
          </Button>
        </Space>
      }
    >
      <div style={{ minHeight: '300px' }}>
        {/* 说明文字 */}
        <Paragraph type="secondary" style={{ marginBottom: 16 }}>
          AI根据文章内容生成了多个不同风格的标题建议，点击选择您喜欢的标题
        </Paragraph>

        {/* 错误提示 */}
        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            closable
            onClose={() => setError(null)}
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 加载状态 */}
        {loading && (
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">AI正在思考中，请稍候...</Text>
            </div>
          </div>
        )}

        {/* 标题列表 */}
        {!loading && titles.length > 0 && (
          <List
            dataSource={titles}
            renderItem={(title, index) => (
              <List.Item
                onClick={() => handleSelectTitle(title)}
                style={{
                  cursor: 'pointer',
                  padding: '16px',
                  borderRadius: '8px',
                  border: selectedTitle === title ? '2px solid #1890ff' : '2px solid transparent',
                  backgroundColor: selectedTitle === title ? '#e6f7ff' : '#fafafa',
                  marginBottom: '8px',
                  transition: 'all 0.3s'
                }}
                className="title-suggestion-item"
              >
                <List.Item.Meta
                  avatar={
                    <div style={{
                      width: 32,
                      height: 32,
                      borderRadius: '50%',
                      backgroundColor: selectedTitle === title ? '#1890ff' : '#d9d9d9',
                      color: '#fff',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontWeight: 'bold',
                      transition: 'all 0.3s'
                    }}>
                      {selectedTitle === title ? <CheckOutlined /> : index + 1}
                    </div>
                  }
                  title={
                    <Space>
                      <Text strong style={{ fontSize: 16 }}>
                        {title}
                      </Text>
                      {TITLE_STYLES[index] && (
                        <Tag color={TITLE_STYLES[index].color}>
                          {TITLE_STYLES[index].label}
                        </Tag>
                      )}
                    </Space>
                  }
                  description={
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {title.length} 字
                    </Text>
                  }
                />
              </List.Item>
            )}
          />
        )}

        {/* 空状态 */}
        {!loading && titles.length === 0 && !error && (
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <BulbOutlined style={{ fontSize: 48, color: '#d9d9d9', marginBottom: 16 }} />
            <div>
              <Text type="secondary">暂无标题建议</Text>
            </div>
            <Button
              type="primary"
              onClick={handleGenerate}
              style={{ marginTop: 16 }}
            >
              生成标题建议
            </Button>
          </div>
        )}
      </div>

      <style jsx>{`
        .title-suggestion-item:hover {
          background-color: ${selectedTitle ? '#e6f7ff' : '#f0f0f0'} !important;
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      `}</style>
    </Modal>
  )
}

export default TitleSuggestionModal
